import pygame
import random

# 初始化 Pygame
pygame.init()

# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")

# 定义蛇的初始位置和大小
snake_x = 100
snake_y = 100
snake_width = 20
snake_height = 20

# 定义蛇的移动速度
snake_speed = 5

# 定义食物的初始位置和大小
food_x = random.randint(0, WINDOW_WIDTH - snake_width)
food_y = random.randint(0, WINDOW_HEIGHT - snake_height)
food_width = 20
food_height = 20

# 定义游戏时钟
clock = pygame.time.Clock()

# 定义游戏结束标志
game_over = False

# 游戏循环
while not game_over:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    # 获取键盘输入
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        snake_x -= snake_speed
    elif keys[pygame.K_RIGHT]:
        snake_x += snake_speed
    elif keys[pygame.K_UP]:
        snake_y -= snake_speed
    elif keys[pygame.K_DOWN]:
        snake_y += snake_speed

    # 绘制游戏界面
    window.fill(WHITE)
    pygame.draw.rect(window, GREEN, [food_x, food_y, food_width, food_height])
    pygame.draw.rect(window, BLACK, [snake_x, snake_y, snake_width, snake_height])

    # 检测蛇是否吃到了食物
    if snake_x < food_x + food_width and snake_x + snake_width > food_x and snake_y < food_y + food_height and snake_y + snake_height > food_y:
        food_x = random.randint(0, WINDOW_WIDTH - snake_width)
        food_y = random.randint(0, WINDOW_HEIGHT - snake_height)

    # 更新游戏界面
    pygame.display.update()

    # 控制游戏帧率
    clock.tick(60)

# 退出 Pygame
pygame.quit()